import { Singleton } from "./Singleton";

export class UrlUtil extends Singleton {
  public data: Map<string, string>;

  constructor() {
    super();
  }

  getAllQueryString() {
    var url = window.location.search; //获取url中"?"符后的字串
    var theRequest = new Object();
    if (url.indexOf("?") != -1) {
      var strs = url.split("&");
      for (var i = 0; i < strs.length; i++) {
        theRequest[strs[i].split("=")[0]] = strs[i].split("=")[1];
      }
    }
    return theRequest;
  }

  getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]);
    return null;
  }

  //设置本页面url
  setUrl(paramName, replaceWith,isRefresh=false) {
    var oUrl = window.location.href.toString();
    if (paramName && replaceWith) {
      if (oUrl.indexOf(paramName + "=" + replaceWith) > 1) {
        return;
      }
    }
    if (oUrl.indexOf("&" + paramName + "=") > 0) {
      var re = eval("/(&" + paramName + "=)([^&]*)/gi");
      var nUrl = oUrl.replace(re, "&" + paramName + "=" + replaceWith);
    } else {
      if (oUrl.indexOf("?") > 0) {
        var nUrl = oUrl + "&" + paramName + "=" + replaceWith;
      } else {
        var nUrl = oUrl + "?" + paramName + "=" + replaceWith;
      }
    }
    // this.location = nUrl;
    if (isRefresh) {
      window.location.href = nUrl;
    }
    var stateObject = { id: "" };
    var title = "";
    history.replaceState(stateObject, title, nUrl);
  }
}
